Ext.namespace('com.youku.ad.common.basic.CitySelectorWin');
com.youku.ad.common.basic.CitySelectorWin=Ext.extend(Ext.Window, {
	pthis:null,
	initComponent: function() {
		
		this.addEvents('onClickSetValue');
		
		//一级选项
		var store = this.store = new Ext.data.JsonStore({
		    autoDestroy: true,
		    url : globalCtx+'/common/getCities',
		    root: 'invdata',
		    idProperty: 'id',
		    fields: ['id','name']
		});
		store.load();
		var tpl = new Ext.XTemplate(
			'<div class="ct-two-level-selector-panel">',
				'<ul>',
	                '<tpl for=".">',
	                    '<li class="two-level-selector-panel_item">',
	                        '<b><input class="top-check-cl" type="checkbox" value="{id}">{name}</b>',
	                    '</li>',
	                '</tpl>',
	            '</ul>',
	        '<div>'
	    );
		
		var contextMenu = new Ext.menu.Menu({items: []});
		
		//一级DataView
		var dataview = this.dataview = new Ext.DataView({
			store: store,
			tpl: tpl,
		    frame:true,
		    width:880,
		    autoHeight:true,
		    collapsible:true,
		    layout:'fit',
		    title:'Simple DataView',
		    itemSelector: 'li.two-level-selector-panel_item',
		    autoScroll  : true,
			cls: 'two-level-selector-panel',
			overClass   : 'two-level-selector-panel-hover',
			selectedClass: 'two-level-selector-panel-select',
			listeners: {
				click: {
					scope: this,
					fn:  function(dv, index, n, e) {
					    //判断二级菜单是否汆子，若不存在就不往二级菜单里添加内容
						var bool = Ext.getCmp('city').isVisible();
						if(bool)
							this.dataview_sub.store.loadData(store.data.items[index].json);
			    	}
				},
				contextmenu: {
					scope: this,
					fn:  function(dv, index, n, e) {e.stopEvent();}
				}
			}
	    });
		
	
		
		//二级store
		var store_sub = new Ext.data.Store({
		    reader: new Ext.data.JsonReader({
				totalProperty: 'id',
				idProperty:'id',
				root: 'sub',
				fields: [
					{name: 'id'},{name: 'name'}
				]
			}),
			listeners: {
				load: {
					scope: this,
					fn: function() {
						this._onSubLoadOver();
					}
				}
			}
		});
		var tpl_S = new Ext.XTemplate(
			'<div class="two-level-selector-panel">',
				'<ul>',
	                '<tpl for=".">',
	                    '<li class="two-level-selector-panel_item">',
	                        '<b>{name}</b>',
	                    '</li>',
	                '</tpl>',
	            '</ul>',
	        '<div>'
	    );
		
		//二级
		var dataview_sub = this.dataview_sub = new Ext.DataView({
			store: store_sub,
			id:'sub_panel',
			tpl: tpl_S,
		    frame:true,
		    width:80,
		    autoHeight:true,
		    collapsible:true,
		    layout:'fit',
		    title:'Simple DataView',
		    itemSelector: 'li.two-level-selector-panel_item',
		    autoScroll  : true,
		    multiSelect : true,
		    singleSelect: true,
		    simpleSelect: true,
			cls: 'two-level-selector-panel',
			overClass   : 'two-level-selector-panel-hover',
			selectedClass: 'two-level-selector-panel-select',
			listeners: {
				click: {
					scope: this,
					fn:  function(dv, index, node, e) {
						var r = dv.store.data.items[index].data;
						var parentData = {};
						parentData.id = dv.store.reader.jsonData.id;
						parentData.name = dv.store.reader.jsonData.name;
						
						//从二级单位选择到最右侧
						if(dv.isSelected(node)) {//选中
							this._onSelectedASubLevel(parentData, r);
						}
						else {//取消选中
							this._onDeSelectedASubLevel(parentData, r);
						}
			    	}
				},
				containerclick: function(dv, e) {
					e.stopEvent();
				}
				
			}
	    });
		
		//右侧已经选择树
		var rootNode = this.rootNode = new Ext.tree.TreeNode({text: 'Root', id:'0'});
		var selectedGrid = new Ext.ux.tree.TreeGrid({
			region: 'center',
	        autoScroll: true,
	        enableDD: true,
	        enableSort: false,
	        columns:[
		        {header: '名称',dataIndex: 'name',width: 100},
		        {header: '删除',width: 40, dataIndex: 'id',
		        	tpl: new Ext.XTemplate('{duration:this.formatDeleteAction}', {
		        		formatDeleteAction: function(v) {
		        			return '<font class="eddy-grid-link" style="cursor: pointer;text-decoration: underline;color: #379337;font-weight: bold;">删除</font>';
		                }
		            })
		        }
		    ],
	        root: rootNode,
	        listeners: {
	        	click: {
	        		scope: this,
	        		fn: function(node, e) {
	        			var target = e.getTarget();
						var targetEl=Ext.get(target);
						if(targetEl.hasClass("eddy-grid-link")) {
							//删除树结点
							this.deleteTreeNode(node.id);
						}
						e.stopEvent();
	        		}
	        	}
	        }
		});

		var all_ckbox = this.all_ckbox = new Ext.form.Checkbox({ 
			 boxLabel: '选择全部', 
			 name: 'checkedAll',
    		 listeners:{
				'check':{
					scope: this,
		    		fn: function(cb, checked) {
		    			var all_items = dataview.getEl().dom.getElementsByTagName("input");//选择全部一级菜单：checkbox
		    			var rs = this.dataview.store.data.items;//选择全部一级菜单对象
		    			var bool = Ext.getCmp('city').isVisible();//是省份还是城市
						for(var i = 0; i < all_items.length;i++) {
							all_items[i].checked = checked;//设置一级菜单选中
							//将所有数据添加到最右边已选择框中
							if(checked)
								this._onSelectedATopLevel(rs[i].data,bool,true);//父亲节点、是城市还是省份、是否全选
							else
								this._onDeSelectATopLevel(rs[i].data,bool);
						}
					}
				}
			}
		});
		
		var tbar = this.tbar = new Ext.Toolbar({
			 xtype: 'fieldset',
			 layout: 'hbox',
			 height:25,
			 items: [
		         {
		        	 xtype: 'radiogroup',id: 'selRadio',width:220,
					 items:[
					     {boxLabel: '省份', name: 'rb-auto', inputValue: '1',checked:true},
					     {boxLabel: '城市', name: 'rb-auto', inputValue: '0'},
					     {boxLabel: 'A级城市', name: 'rb-auto', inputValue: '2'}
					 ],
					  listeners: {  
					    	scope:this,
							change: function() {
								var retv = this.getWin_state();//设置：城市和省份的切换
								if(retv == 1){
								   Ext.getCmp('city').hide();
								   Ext.getCmp('province').show();
								   this.removeAll();
								   this.store_filterBy('1');//初始化数据
						    	   this.selectPanel.doLayout(true);
								}else if(retv == 0){
									Ext.getCmp('city').show();
									Ext.getCmp('province').show();
									this.removeAll();
									this.store_filterBy('0');//初始化数据
									this.selectPanel.doLayout(true);
								}else if(retv == 2){
									Ext.getCmp('city').hide();
									Ext.getCmp('province').hide();
									this.removeAll();
									this.store_filterBy('2');//初始化数据
									this.selectPanel.doLayout(true);
								}
							}
						}
		         },
		         {
		        	 xtype:'checkboxgroup',
		        	 items:[all_ckbox]
		         }
	         ]
		});
		
		
		var selectPanel = this.selectPanel = new Ext.FormPanel({
	        maximizable: true,
	        width: 560,
	        height: 340,
	        layout: 'fit',
	        closeAction:'hide',
	        plain: true,
	        buttonAlign: 'center',
	        layout: 'hbox',
	        layoutConfig: {
	            padding:'5',
	            align:'stretch'
	        },
	        defaults:{margins:'0 5 0 0'},
	        tbar:tbar,
	        items:[
	           {
	        	   flex: 1,
	        	   title: '省份',
	        	   id:'province',
	        	   layout: 'fit',
	        	   plain: true,
	        	   autoScroll: true,
	        	   items:[dataview]
	           },
	           {
	        	   flex: .5,
	        	   title: '城市',
	        	   id:'city',
	        	   plain: true,
	        	   autoScroll: true,
	        	   items:[dataview_sub]
	           },
	           {
	        	   flex: 0.7,
	        	   title: '已选择',
	        	   layout: 'fit',
	        	   items:[selectedGrid]
	           }
	        ],
	        buttons: [
	            {
		            text: '确认',
		            scope: this,
		            handler: function() {
		            	var count = this.getSelectedDataByids();
		            	if(count == '')
		            		this.pthis.setSelectCityAndType_count(0,'city');
		            	else
		            		this.pthis.setSelectCityAndType_count(count.split(",").length,'city');
		            	this.hide();
		            }
		        }, 
		        {
		            text: '清空',
		            scope: this,
		            handler: function(){
		            	this.removeAll();
		            }
		        }
	        ],
	        listeners: {
	        	afterrender: {
	        		scope: this,
	        		fn: function() {
	        			dataview.getEl().on('click', function(e, t) {
		        	    	if(e.target.checked) {
		        				dataview.select(store.getById(e.target.value), true, true);
		        				var r = dataview.store.getById(e.target.value);
		        				
		        				var bool = Ext.getCmp('city').isVisible();
		        				this._onSelectedATopLevel(r.data,bool);
		        			}
		        			else {
		        				dataview.deselect(store.getById(e.target.value));
		        				var r = dataview.store.getById(e.target.value);
		        				
		        				var bool = Ext.getCmp('city').isVisible();
		        				
		        				//当有一个，取消选择的全选按钮就失效
		        				this.all_ckbox.el.dom.checked = false;
		        				this.all_ckbox.checked = false;
		        				
		        				this._onDeSelectATopLevel(r.data,bool);
		        			}
		        		}, this, {delegate: 'input.top-check-cl'});
	        		}
	        	}
	        }
			
		})
		
		Ext.apply(this, {  
			autoScroll: true,
			modal: true,
			layout: 'form',
			title: '选择',
			items:[selectPanel]
        });
		
        //调用父类构造函数（必须）  
		com.youku.ad.common.basic.CitySelectorWin.superclass.initComponent.apply(this, arguments);
	},
	
	/**
	 * private 方法
	 * 选中一个二级选择后的处理
	 */
	_onSelectedASubLevel: function(pNodeAttr, subAttr) {
		if(this.rootNode.findChild("id", subAttr.id, true)) {//如果已经选择，则不加
			return;
		}
	
		//如果树上没有父结点，则先加上父结点
		if(!this.rootNode.findChild("id", pNodeAttr.id)) {
			var pnode = new Ext.tree.TreeNode({id: pNodeAttr.id, name: pNodeAttr.name, leaf :false, text: pNodeAttr.name});
			//将结点放到第一位
			if(this.rootNode.childNodes.length == 0) {
				this.rootNode.appendChild(pnode);
			}
			else {
				this.rootNode.insertBefore(pnode, this.rootNode.childNodes[0]);
			}
		}
		
		//找到该二级结点的父结点，然后加到树上
		var pNode = this.rootNode.findChild("id", pNodeAttr.id);
		var node = new Ext.tree.TreeNode({id: subAttr.id, name: subAttr.name, leaf :true, text: subAttr.name});
		pNode.appendChild(node);
		pNode.expand();
		
		//如果二级结点下所有的都选中了，则自动选中上级
		if(this.dataview_sub.getSelectedRecords().length == this.dataview_sub.store.getCount()) {
			var r = this.dataview.store.getById(pNodeAttr.id);
			this.dataview.select(r, true, true);
			var acheck = this.dataview.getEl().query('input.top-check-cl[value="' + pNodeAttr.id + '"]');
			acheck[0].checked = true;
		}
	},
	
	/**
	 * 取消选中一个二级项
	 */
	_onDeSelectedASubLevel: function(pNodeAttr, subAttr) {
		var node = this.rootNode.findChild("id", subAttr.id, true);
		node.remove(true);
		
		//FIXME 如果二级结点没有一个选中，考虑是否需要取消上级选中
		if(this.dataview_sub.getSelectedRecords().length == 0) {
		}
	},
//	
//	/**
//	 * private 方法
//	 * 选中一个二级选择后的处理
//	 */
//	_onSelectedASubLevel_A: function(subAttr) {
//		var node = this.rootNode.findChild("id", topAttr.id, true);
//		if(node) {
//			node.removeAll(true);
//			node.remove(true);
//		}
//		
//		var pnode = new Ext.tree.TreeNode({id: topAttr.id, name: topAttr.name, leaf :false, text: topAttr.name});
//		//将结点放到第一位
//		if(this.rootNode.childNodes.length == 0) {
//			this.rootNode.appendChild(pnode);
//		}
//		else {
//			this.rootNode.insertBefore(pnode, this.rootNode.childNodes[0]);
//		}
//	},
	/**
	 * private 方法
	 * 选中一个一级选项后的处理
	 * 如果树上没有该结点，增加该结点
	 * 将其下的所有二级结点加到对应的树结点上
	 */
	_onSelectedATopLevel: function(topAttr,bool,type) {
		var node = this.rootNode.findChild("id", topAttr.id, true);
		if(node) {
			node.removeAll(true);
			node.remove(true);
		}
		
		var pnode = new Ext.tree.TreeNode({id: topAttr.id, name: topAttr.name, leaf :false, text: topAttr.name});
		//将结点放到第一位
		if(this.rootNode.childNodes.length == 0) {
			this.rootNode.appendChild(pnode);
		}
		else {
			this.rootNode.insertBefore(pnode, this.rootNode.childNodes[0]);
		}
		//若true（城市）、false（省份）
		if(bool){
			var r = this.dataview.store.getById(topAttr.id);
			for(var i = 0; i < r.json.sub.length; i++) {
				var node = new Ext.tree.TreeNode({id: r.json.sub[i].id, name: r.json.sub[i].name, leaf :true, text: r.json.sub[i].name});
				pnode.appendChild(node);
			}
			if(!type)
				pnode.expand();
			
			//设置子项为选中状态
			pnode.eachChild(function(n) {
				var r = this.dataview_sub.store.getById(n.id);
				this.dataview_sub.select(r, true, true);
			}, this);
		}
	},
	
	/**
	 * private 方法
	 * 取消选中一个上级选项
	 * 此时应该在右删除对应的树结点
	 */
	_onDeSelectATopLevel: function(topAttr) {
		var node = this.rootNode.findChild("id", topAttr.id, true);
		if(node) {
			//设置子项为非选中状态
			node.eachChild(function(n) {
				var r = this.dataview_sub.store.getById(n.id);
				this.dataview_sub.deselect(r, true, true);
			}, this);
			
			node.remove();
		} 
	},
	
	/**
	 * 删除树结点
	 */
	deleteTreeNode: function(nodeId) {
		//当有一个，取消选择的全选按钮就失效
		this.all_ckbox.el.dom.checked = false;
		this.all_ckbox.checked = false;
		
		//如果当前二级列表中有所删除项，则将该二级项设置为非选中状态
		var r = this.dataview_sub.store.getById(nodeId);
		if(r) {
			this.dataview_sub.deselect(r, true, true);
		}
		
		var node = this.rootNode.findChild("id", nodeId, true);
		//如果删除的是个一级结点，需要将一级dataview中对应的设置为非选中状态
		if(!node.leaf) {
			var r = this.dataview.store.getById(nodeId);
			if(r) {
				this.dataview.deselect(r, true, true);
				
				//设置选择框为未选中状态
				var acheck = this.dataview.getEl().query('input.top-check-cl[value="' + nodeId + '"]');
				acheck[0].checked = false;
			}
		}
		
		node.remove();
		if(!node.leaf) {
			this.dataview_sub.store.removeAll();
			this.dataview_sub.store.loadData(r.json);
		}
	},
	
	/**
	 * 二级数据加载完成
	 * 此时需要设置是否需要选中相关项
	 */
	_onSubLoadOver: function() {
		var pId = this.dataview_sub.store.reader.jsonData.id;
		var node = this.rootNode.findChild("id", pId, true);
		if(node) {//如果树上有父结点，则设置哪些子项需要选中
			node.eachChild(function(n) {
				var r = this.dataview_sub.store.getById(n.id);
				this.dataview_sub.select(r, true, true);
			}, this);
		}
	},
	
	/**
	 * 得到已经选择的数据
	 * 以右侧树为准
	 */
	getSelectedData: function() {
		var retObj = new Array();
		this.rootNode.eachChild(function(pNode) {
			var topLevel = {id: pNode.attributes.id, name: pNode.attributes.name};
			topLevel.sub = new Array();
			pNode.eachChild(function(n) {
				this.push({id: n.attributes.id, name: n.attributes.name});
			}, topLevel.sub);
			
			this.push(topLevel);
		}, retObj);
		return retObj;
	},
	initMethod: function() {
		var retv = this.getWin_state();//设置：城市和省份的切换
		if(retv == 1){
		   Ext.getCmp('city').hide();
    	   this.selectPanel.doLayout(true);
		}else{
			Ext.getCmp('city').show();
			this.selectPanel.doLayout(true);
		}
	},
	store_filterBy:function(kv){
		if(kv == '0' || kv == '1'){
			this.store.filterBy(function(record,id){   
				record.set('name', record.get('name'));
	    	    return true;      
	       })
		}else{
			this.store.filterBy(function(record,id){   
			  
	       })
		}
	},
	/**
	 * 清空界面所有元素
	 */
	removeAll:function(){
		this.dataview.refresh();//初始化主界面
		this.dataview_sub.store.removeAll();//清空城市选择面板
		this.all_ckbox.setValue(false);//全选按钮制空
		this.rootNode.removeAll(true);//清空已经选择界面
	},
	/**
	 * 获取界面所有数据，并以aaa,bbb,ccc的格式返回
	 */
	getSelectedDataByids:function(){
    	var strAllIds="";
		var datas = this.getSelectedData();
    	for(var i = 0 ; i < datas.length; i++){
    		var subdatas = datas[i].sub;
    		if(subdatas.length > 0){
    			for(var j = 0 ; j < subdatas.length; j++){
    				strAllIds += strAllIds==''?subdatas[j].id:","+subdatas[j].id;//二级节点
        		}
    		}
    		else
    			strAllIds += strAllIds==''?datas[i].id:","+datas[i].id;//二级节点
    	}
    	return strAllIds;
	},
	/**
	 * 返回是否全选状态
	 */
	isSelAllCheckdBox:function(){
		var isAll = this.all_ckbox.getValue();
		return isAll;
	},
	/**
	 * 返回是选择了城市还是省份
	 */
	getWin_state:function(){
		//retSelValue 1"省份" 0"城市"
		var retSelValue;
		var sex = Ext.getCmp('selRadio');
		sex.eachItem(function(item){
		    if(item.checked===true){
		    	retSelValue =item.inputValue;
		    }
		 }); 
	  return retSelValue;
	}
});